﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace EasyFramework.Base
{
    public class ConfigHelper
    {
        /// <summary>
        /// 功能: 通过key获取appsetting中对应项的值
        /// [2011-12-14 22:29:15 zhandy]<para />
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hashKey"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public T GetConfigValue<T>(string hashKey, T defaultValue)
        {
            try
            {
                foreach (string key in ConfigurationManager.AppSettings.AllKeys)
                {
                    if (key == hashKey)
                        return (T)Convert.ChangeType(ConfigurationManager.AppSettings[hashKey], typeof(T));
                }
                return defaultValue;
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }



        /// <summary>
        /// 修改AppSettings中配置项的内容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void SetConfigValue(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (config.AppSettings.Settings[key] != null)
                config.AppSettings.Settings[key].Value = value;
            else
                config.AppSettings.Settings.Add(key, value);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
